package com.foreverwin.mes.so.service.impl;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.foreverwin.mes.common.constants.HandleBOConstants;
import com.foreverwin.mes.core.base.FrontPage;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.DateUtil;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.meapi.model.Item;
import com.foreverwin.mes.meapi.service.ItemService;
import com.foreverwin.mes.meapi.service.ResrceService;
import com.foreverwin.mes.so.controller.RecipeController;
import com.foreverwin.mes.so.model.Recipe;
import com.foreverwin.mes.so.model.RecipeResrceItemRel;
import com.foreverwin.mes.so.mapper.RecipeResrceItemRelMapper;
import com.foreverwin.mes.so.model.RecipeResrceItemRelView;
import com.foreverwin.mes.so.service.RecipeResrceItemRelService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.foreverwin.mes.so.service.RecipeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Syngna
 * @since 2020-02-04
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RecipeResrceItemRelServiceImpl extends ServiceImpl<RecipeResrceItemRelMapper, RecipeResrceItemRel> implements RecipeResrceItemRelService {

    private final Logger logger = LoggerFactory.getLogger(RecipeResrceItemRelServiceImpl.class);

    @Autowired
    private RecipeResrceItemRelMapper recipeResrceItemRelMapper;

    @Autowired
    private ItemService itemService;

    @Autowired
    private RecipeService recipeService;

    @Autowired
    private ResrceService resrceService;

    @Override
    public Page<RecipeResrceItemRel> selectPage(FrontPage<RecipeResrceItemRel> frontPage, RecipeResrceItemRel recipeResrceItemRel) {
        EntityWrapper<RecipeResrceItemRel> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(recipeResrceItemRel);
        return super.selectPage(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<RecipeResrceItemRel> selectList(RecipeResrceItemRel recipeResrceItemRel) {
        EntityWrapper<RecipeResrceItemRel> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(recipeResrceItemRel);
        return super.selectList(queryWrapper);
    }

    /**
     * @param site
     * @param resource
     * @param item
     * @return
     */
    @Override
    public List<RecipeResrceItemRelView> findRelation(String site, String resource, String item) {
        Locale locale = LocaleContextHolder.getLocale();
        List resultList = recipeResrceItemRelMapper.findRelation(locale.getLanguage(), site, resource, item);
        return resultList;
    }


    /**
     * @param site
     * @param item
     * @param resource
     * @param recipeBo
     * @return
     */
    @Override
    public String saveRelation(String site, String user, String item, String resource, String recipeBo) throws BusinessException {
        String resultMsg;
        if(StringUtils.isBlank(item)) {
            throw BusinessException.build("物料不能为空");
        }
        if(StringUtils.isBlank(resource)) {
            throw BusinessException.build("设备编号不能为空");
        }
        List<Item> itemPo = itemService.selectList(new EntityWrapper<Item>()
                .eq(Item.SITE, site)
                .eq(Item.ITEM, item)
                .eq(Item.CURRENT_REVISION, "true"));
        if(itemPo == null || itemPo.size() == 0) {
            throw BusinessException.build("物料" + item + "当前版本不存在");
        }
        Recipe recipe = recipeService.selectById(recipeBo);
        if(recipe == null) {
            throw BusinessException.build("配方" + StringUtils.trimHandle(recipeBo) + "版本【" + StringUtils.trimRevision(recipeBo) + "】不存在");
        }
        if(resrceService.selectById(StringUtils.genHandle(HandleBOConstants.RESOURCE_BO, site, resource)) == null) {
            throw BusinessException.build("资源" + resource + "】不存在");
        }

        String itemBo = StringUtils.genHandle(HandleBOConstants.ITEM_BO, site, item, "#");
        String itemRecipeBo = resource + ";" + item + ";" + ";" + recipeBo;//废掉时间戳记，只能存在一笔唯一值 + ";" + DateUtil.getTimeString(); // 加个时间戳记防止同一个配方来回使用
        Wrapper<RecipeResrceItemRel> wrapper = new EntityWrapper<RecipeResrceItemRel>()
                .eq(RecipeResrceItemRel.SITE, site)
                .eq(RecipeResrceItemRel.RESRCE, resource)
                .eq(RecipeResrceItemRel.ITEM, item);
        List<RecipeResrceItemRel> resultList = this.selectList(wrapper);
        Date now = new Date();
        if (resultList.size() > 0) {
            if(resultList.get(0).getRecipeBo().equals(recipeBo)) {
                return "当前维护关系已存在！";
            }
            // 说明当前关联关系存在，更新RECIPE
            for (int i = 0; i < resultList.size(); i++) {
                RecipeResrceItemRel recipeResrceItemRel = resultList.get(i);
                //resrceMtrlSpec.setEndTime(DateUtil.getNowDate());
                recipeResrceItemRel.setRecipeBo(recipeBo);
                recipeResrceItemRel.setUpdater(user);
                recipeResrceItemRel.setModifiedDateTime(now);
                this.updateById(recipeResrceItemRel);
                logger.info("RECIPE_RELATION_OPERATION: 用户【{}】更新设备【{}】物料【{}】使用的配方【{}】为【{}】成功!", user, resource, item, recipeResrceItemRel.getRecipeBo(), recipeBo);
            }
            resultMsg = "更新设备【" + resource + "】物料【" + item + "】使用的配方成功!";
        } else {
            // 新增一笔当前用的关联关系
            RecipeResrceItemRel newRecipeResrceItemRel = new RecipeResrceItemRel();
            newRecipeResrceItemRel.setHandle(itemRecipeBo); // 资源;物料
            newRecipeResrceItemRel.setSite(site);
            newRecipeResrceItemRel.setCreator(user);
            newRecipeResrceItemRel.setUpdater(user);
            newRecipeResrceItemRel.setItem(item);
            newRecipeResrceItemRel.setResrce(resource);
            newRecipeResrceItemRel.setItemBo(itemBo);
            newRecipeResrceItemRel.setCreatedDateTime(now);
            newRecipeResrceItemRel.setModifiedDateTime(now);
            newRecipeResrceItemRel.setItemVersion("#");
            newRecipeResrceItemRel.setRecipeBo(recipeBo);
            this.insert(newRecipeResrceItemRel);
            resultMsg = "新增设备【" + resource + "】物料【" + item + "】使用的配方成功!";
            logger.info("RECIPE_RELATION_OPERATION: 用户【{}】新增设备【{}】物料【{}】使用的配方【{}】成功!", user, resource, item, recipeBo);
        }
        return resultMsg;
    }
}